package org.drushpal.view
{
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import org.drushpal.DrushPalEvent;
	import org.drushpal.model.SettingsModel;
	import org.drushpal.model.enum.DrushCommand;
	import org.drushpal.service.CloseConnectionEvent;
	import org.drushpal.service.DrushService;
	import org.drushpal.util.LinkEvent;
	import org.robotlegs.mvcs.Mediator;
	
	public class ControlPanelMediator extends Mediator
	{
		
		public var connected:Boolean=false;
		public var drush:DrushService;
		[Inject]public var settingsModel:SettingsModel;
		[Inject]public var drushService:DrushService;
		[Inject]public var controlPanel:ControlPanel;
		public function ControlPanelMediator()
		{
			
		}
		
		override public function onRegister():void{
			connect();
			eventMap.mapListener(controlPanel.btnClose,MouseEvent.CLICK,onClose);
			eventMap.mapListener(controlPanel.btnOpenSettings,MouseEvent.CLICK,onOpenSettings);			
			eventMap.mapListener(controlPanel,LinkEvent.OPEN,onLink);
		}
		
		private function onLink(event:LinkEvent):void{
			if(settingsModel.settings.openInExternalBrowser){
				navigateToURL(new URLRequest(event.url));
			}else{
				controlPanel.browser.browser.location = event.url;
			}
		}
		
		private function onOpenSettings(event:MouseEvent):void{
			eventDispatcher.dispatchEvent(new DrushPalEvent(DrushPalEvent.OPEN_SETTINGS));
		}
		
		private function onClose(event:MouseEvent):void{
			drushService.stop();			
		}
		
		public function connect():void
		{
			controlPanel.browser.browser.location = controlPanel.connection.uri;
			drushService.start(controlPanel.connection);
			drushService.run(DrushCommand.STATUS);
		}	
		
		
	}
}